package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.Instance.L1PcInstance;

/**
 * PC 鬼魂模式處理 時間軸
 *
 * @author dexc
 *
 */
public class PcGhostTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(PcGhostTimer.class
			.getName());

	/**
	 * 檢查鬼魂模式時間
	 *
	 * @param tgpc
	 * @param time
	 */
	private static void check(final L1PcInstance tgpc, final Integer time) {
		if (time > 0) {
			// 角色死亡加入移出清單
			if (!tgpc.isDead()) {
				// 更新
				tgpc.set_ghostTime(-1);

			} else {
				// 更新
				tgpc.set_ghostTime(time);
			}

		} else {
			// 時間到
			tgpc.set_ghostTime(-1);

			// 未斷線移除狀態
			if (tgpc.getNetConnection() != null) {
				outPc(tgpc);
			}
		}
	}

	/**
	 * 離開鬼魂模式(傳送回出發點)
	 *
	 * @param tgpc
	 */
	private static void outPc(final L1PcInstance tgpc) {
		try {
			if (tgpc != null) {
				tgpc.makeReadyEndGhost();
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
	}

	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<L1PcInstance> all = L1World.getInstance()
					.getAllPlayers();
			// 不包含元素
			if (all.isEmpty()) {
				return;
			}

			for (final L1PcInstance tgpc : all) {
				// 非鬼魂狀態
				if (!tgpc.isGhost()) {
					continue;
				}

				int time = tgpc.get_ghostTime();
				time--;
				check(tgpc, time);
				Thread.sleep(1);
			}

			/*
			 * for (final L1PcInstance tgpc : all) { // 非鬼魂狀態 if
			 * (!tgpc.isGhost()) { continue; }
			 *
			 * int time = tgpc.get_ghostTime(); time--; check(tgpc, time);
			 * Thread.sleep(1); }
			 */

		} catch (final Exception e) {
			_log.log(Level.SEVERE, "PC 鬼魂模式處理時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final PcGhostTimer pcHprTimer = new PcGhostTimer();
			pcHprTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 1100;// 1秒
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,
				timeMillis, timeMillis);
	}
}
